import * as THREE from 'three';

// 车辆状态接口
export interface CarState {
  position: THREE.Vector3;
  rotation: number;
  speed: number;
  maxSpeed: number;
  acceleration: number;
  turnSpeed: number;
  isBreaking: boolean;
}

// 键盘控制状态
export interface KeyboardState {
  forward: boolean;
  backward: boolean;
  left: boolean;
  right: boolean;
  brake: boolean;
  lightToggle: boolean;
}

// 车辆控制器类
export class CarController {
  private car: CarState;
  private keys: KeyboardState;
  private carMesh: THREE.Group;
  private keyboardListeners: { [key: string]: (event: KeyboardEvent) => void } = {};

  constructor(carMesh: THREE.Group) {
    this.carMesh = carMesh;
    
    // 初始化车辆状态
    this.car = {
      position: new THREE.Vector3(-40, 0.5, -10), // 调整到安全位置
      rotation: 0,
      speed: 0,
      maxSpeed: 8,
      acceleration: 15,
      turnSpeed: 2,
      isBreaking: false
    };

    // 初始化键盘状态
    this.keys = {
      forward: false,
      backward: false,
      left: false,
      right: false,
      brake: false,
      lightToggle: false
    };

    this.setupKeyboardControls();
  }

  // 设置键盘控制
  private setupKeyboardControls(): void {
    const onKeyDown = (event: KeyboardEvent) => {
      switch (event.code) {
        case 'KeyW':
        case 'ArrowUp':
          this.keys.forward = true;
          break;
        case 'KeyS':
        case 'ArrowDown':
          this.keys.backward = true;
          break;
        case 'KeyA':
        case 'ArrowLeft':
          this.keys.left = true;
          break;
        case 'KeyD':
        case 'ArrowRight':
          this.keys.right = true;
          break;
        case 'Space':
          this.keys.brake = true;
          event.preventDefault();
          break;
        case 'KeyL':
          if (!this.keys.lightToggle) {
            this.keys.lightToggle = true;
            this.onLightToggle?.();
          }
          break;
      }
    };

    const onKeyUp = (event: KeyboardEvent) => {
      switch (event.code) {
        case 'KeyW':
        case 'ArrowUp':
          this.keys.forward = false;
          break;
        case 'KeyS':
        case 'ArrowDown':
          this.keys.backward = false;
          break;
        case 'KeyA':
        case 'ArrowLeft':
          this.keys.left = false;
          break;
        case 'KeyD':
        case 'ArrowRight':
          this.keys.right = false;
          break;
        case 'Space':
          this.keys.brake = false;
          break;
        case 'KeyL':
          this.keys.lightToggle = false;
          break;
      }
    };

    document.addEventListener('keydown', onKeyDown);
    document.addEventListener('keyup', onKeyUp);

    // 保存监听器引用以便清理
    this.keyboardListeners['keydown'] = onKeyDown;
    this.keyboardListeners['keyup'] = onKeyUp;
  }

  // 灯光切换回调
  public onLightToggle?: () => void;

  // 更新车辆物理状态
  public update(deltaTime: number): void {
    // 处理加速度
    if (this.keys.forward) {
      this.car.speed = Math.min(this.car.speed + this.car.acceleration * deltaTime, this.car.maxSpeed);
    } else if (this.keys.backward) {
      this.car.speed = Math.max(this.car.speed - this.car.acceleration * deltaTime, -this.car.maxSpeed * 0.5);
    } else if (!this.keys.brake) {
      // 自然减速
      if (this.car.speed > 0) {
        this.car.speed = Math.max(0, this.car.speed - this.car.acceleration * 0.5 * deltaTime);
      } else if (this.car.speed < 0) {
        this.car.speed = Math.min(0, this.car.speed + this.car.acceleration * 0.5 * deltaTime);
      }
    }

    // 处理刹车
    if (this.keys.brake) {
      this.car.isBreaking = true;
      if (this.car.speed > 0) {
        this.car.speed = Math.max(0, this.car.speed - this.car.acceleration * 2 * deltaTime);
      } else if (this.car.speed < 0) {
        this.car.speed = Math.min(0, this.car.speed + this.car.acceleration * 2 * deltaTime);
      }
    } else {
      this.car.isBreaking = false;
    }

    // 处理转向（只有在移动时才能转向）
    if (Math.abs(this.car.speed) > 0.1) {
      if (this.keys.left) {
        this.car.rotation += this.car.turnSpeed * deltaTime * (this.car.speed / this.car.maxSpeed);
      }
      if (this.keys.right) {
        this.car.rotation -= this.car.turnSpeed * deltaTime * (this.car.speed / this.car.maxSpeed);
      }
    }

    // 计算移动方向
    const direction = new THREE.Vector3(
      Math.sin(this.car.rotation),
      0,
      Math.cos(this.car.rotation)
    );

    // 更新位置
    this.car.position.add(direction.multiplyScalar(this.car.speed * deltaTime));

    // 更新车辆网格位置和旋转
    this.carMesh.position.copy(this.car.position);
    this.carMesh.rotation.y = this.car.rotation;
  }

  // 获取车辆状态
  public getCarState(): CarState {
    return { ...this.car };
  }

  // 获取车辆前方位置（用于车灯）
  public getFrontPosition(offset: number = 1.5): THREE.Vector3 {
    const direction = new THREE.Vector3(
      Math.sin(this.car.rotation),
      0,
      Math.cos(this.car.rotation)
    );
    return this.car.position.clone().add(direction.multiplyScalar(offset));
  }

  // 获取车辆前方方向
  public getFrontDirection(): THREE.Vector3 {
    return new THREE.Vector3(
      Math.sin(this.car.rotation),
      -0.1,
      Math.cos(this.car.rotation)
    ).normalize();
  }

  // 获取车辆后方位置（用于尾灯）
  public getRearPosition(offset: number = 1.0): THREE.Vector3 {
    const direction = new THREE.Vector3(
      -Math.sin(this.car.rotation),
      0,
      -Math.cos(this.car.rotation)
    );
    return this.car.position.clone().add(direction.multiplyScalar(offset));
  }

  // 获取左右灯光位置
  public getLightPositions(frontOffset: number = 1.5, sideOffset: number = 0.3) {
    const frontPos = this.getFrontPosition(frontOffset);
    const rearPos = this.getRearPosition(1.0);
    
    const rightDir = new THREE.Vector3(
      Math.cos(this.car.rotation),
      0,
      -Math.sin(this.car.rotation)
    );
    
    return {
      frontLeft: frontPos.clone().add(rightDir.clone().multiplyScalar(-sideOffset)),
      frontRight: frontPos.clone().add(rightDir.clone().multiplyScalar(sideOffset)),
      rearLeft: rearPos.clone().add(rightDir.clone().multiplyScalar(-sideOffset)),
      rearRight: rearPos.clone().add(rightDir.clone().multiplyScalar(sideOffset))
    };
  }

  // 清理资源
  public dispose(): void {
    document.removeEventListener('keydown', this.keyboardListeners['keydown']);
    document.removeEventListener('keyup', this.keyboardListeners['keyup']);
  }
}